package com.jhy.suixianglu.daima20221219;

import com.jhy.suixianglu.daima20221212.ListNode;

/**
 * 给你两个单链表的头节点 headA 和 headB ，
 *          请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点，返回 null 。
 */
public class GetIntersectionNode {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode curA = headA;
        ListNode curB = headB;
        int countA = 0;
        int countB = 0;
        // 统计两个链表当中的长度
        while (curA != null){
            countA++;
            curA = curA.next;
        }
        while (curB != null){
            countB++;
            curB = curB.next;
        }
        curA = headA;
        curB = headB;
        // 以节点A为标准  长度和头节点 交换
        if(countB>countA){
            // 交换长度
           int  countT = countA;
           countA = countB;
           countB = countT;
           // 交换指针
            ListNode temp = curA;
            curA = curB;
            curB = temp;
        }
        // 将A节点的头指针指向和B节点头节点位置指向一致
        int i =countA - countB;
        for (int j = 0; j < i; j++) {
            curA = curA.next;
        }
        // 相等就放回 不相等就下一个节点
        while(curA != null && curB != null){
            if(curA == curB){
                return curA;
            }
            curA = curA.next;
            curB = curB.next;

        }
        return null;
    }
}
